<template>
  <div class="bg-white rounded-lg shadow-sm overflow-hidden">
        <!-- 在搜索区域添加 Form 组件 -->
    <Form :model="searchForm" :labelWidth="120">
       <div class="p-4 border-b border-gray-200">
      <div class="flex flex-wrap items-center gap-4">
        <div class="flex-1 min-w-[200px]">
          <FormItem label="套餐名称">
            <Input v-model="searchForm.name" placeholder="请输入套餐名称" />
          </FormItem>
        </div>
        <div class="w-full sm:w-auto">
          <FormItem label="套餐类型">
            <Select v-model="searchForm.type" placeholder="请选择套餐类型">
              <Option v-for="type in packageTypes" :value="type.value" :key="type.value">{{ type.label }}</Option>
            </Select>
          </FormItem>
        </div>
        <div class="w-full sm:w-auto">
          <FormItem label="所属院区">
            <Select v-model="searchForm.hospitalArea" placeholder="请选择院区">
              <Option v-for="area in hospitalAreas" :value="area.value" :key="area.value">{{ area.label }}</Option>
            </Select>
          </FormItem>
        </div>
        <div class="w-full sm:w-auto">
          <FormItem label="状态">
            <Select v-model="searchForm.status" placeholder="请选择状态">
              <Option value="">全部</Option>
              <Option value="true">启用</Option>
              <Option value="false">禁用</Option>
            </Select>
          </FormItem>
        </div>
        <div class="w-full sm:w-auto">
          <Button type="primary" @click="searchPackages">
            <i class="fa fa-search mr-2"></i>搜索
          </Button>
          <Button @click="resetSearch" class="ml-2">重置</Button>
        </div>
      </div>
    </div>
    </Form>
    <!-- 搜索和筛选区域 -->
   

    <!-- 表格内容区域 -->
    <div class="overflow-x-auto">
      <Table :columns="columns" :data="packageList"  :loading="isLoading">
        <template #name="{ record }">
          <div class="flex items-center">
            <img v-if="record.imageUrl" :src="record.imageUrl" alt="套餐图片" class="w-10 h-10 rounded object-cover mr-3">
            <span>{{ record.name }}</span>
          </div>
        </template>
        <template #type="{ record }">
          {{ getTypeLabel(record.type) }}
        </template>
        <template #hospitalArea="{ record }">
          {{ getAreaLabel(record.hospitalArea) }}
        </template>
        <template #items="{ record }">
          <span v-for="item in record.items" :key="item" class="inline-block bg-blue-100 text-blue-800 text-xs px-2 py-0.5 rounded mr-1 mb-1">
            {{ getItemLabel(item) }}
          </span>
        </template>
        <template #status="{ record }">
          <Switch v-model="record.status" @change="toggleStatus(record)" />
        </template>
        <template #action="{ record }">
          <div class="flex space-x-2">
            <Button type="text" size="small" @click="editPackage(record)">
              <i class="fa fa-edit text-blue-500"></i> 编辑
            </Button>
            <Button type="text" size="small" @click="deletePackage(record)">
              <i class="fa fa-trash text-red-500"></i> 删除
            </Button>
          </div>
        </template>
      </Table>
    </div>

    <!-- 分页区域 -->
    <!-- <div class="px-4 py-3 flex items-center justify-between border-t border-gray-200">
      <div class="hidden sm:flex-1 sm:flex sm:items-center sm:justify-between">
        <div>
          <p class="text-sm text-gray-700">
            显示第 <span class="font-medium">{{ (currentPage - 1) * pageSize + 1 }}</span> 至 <span class="font-medium">{{ Math.min(currentPage * pageSize, total) }}</span> 条，共 <span class="font-medium">{{ total }}</span> 条记录
          </p>
        </div>
        <div>
          <Pagination
            @on-change="handlePageChange"
            @on-page-size-change="handleSizeChange"
            :current="currentPage"
            :page-size="pageSize"
            :total="total"
            show-total
            show-sizer
            :page-sizes="[10, 20, 50, 100]"
            simple />
        </div>
      </div>
    </div> -->
  </div>

 
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'

import { Message } from 'view-ui-plus';
// API服务
import { packageApi } from '@/api/physicalExaminationApi/physicalExamination'

// 状态管理
const editModalVisible = ref(false)
const isEditing = ref(false)
const isLoading = ref(false)

// 搜索表单
const searchForm = reactive({
  name: '',
  type: '',
  hospitalArea: '',
  status: ''
})

// 编辑表单
const editForm = reactive({
  id: '',
  name: '',
  type: '',
  hospitalArea: '',
  price: 0,
  items: [],
  description: '',
  status: true,
  imageUrl: ''
})

// 表单验证规则
const editRules = reactive({
  name: [
    { required: true, message: '请输入套餐名称', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择套餐类型', trigger: 'change' }
  ],
  hospitalArea: [
    { required: true, message: '请选择所属院区', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入套餐价格', trigger: 'blur' },
    { type: 'number', message: '价格必须为数字', trigger: 'blur' }
  ],
  items: [
    { required: true, message: '请至少选择一个套餐项目', trigger: 'change' }
  ]
})

// 分页信息
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 静态数据
const packageTypes = [
  { value: 'elderly', label: '老年人套餐' },
  { value: 'child', label: '儿童套餐' },
  { value: 'female', label: '女性套餐' },
  { value: 'male', label: '男性套餐' },
  { value: 'comprehensive', label: '综合套餐' }
]

const hospitalAreas = [
  { value: 'east', label: '东院' },
  { value: 'west', label: '西院' },
  { value: 'south', label: '南院' },
  { value: 'north', label: '北院' },
  { value: 'central', label: '中心院区' }
]

const checkupItems = [
  { value: 'general', label: '一般检查' },
  { value: 'blood', label: '血常规' },
  { value: 'urine', label: '尿常规' },
  { value: 'biochemistry', label: '生化全套' },
  { value: 'electrocardiogram', label: '心电图' },
  { value: 'ultrasound', label: '腹部超声' },
  { value: 'chestXray', label: '胸部X光' },
  { value: 'ct', label: '胸部CT' },
  { value: 'tcm', label: '中医问诊' }
]

// 表格列定义
const columns = [
  {
    title: '套餐ID',
    key: 'id',
    width: 120
  },
  {
    title: '套餐名称',
    key: 'name',
    width: 200
  },
  {
    title: '套餐类型',
    key: 'type',
    width: 120
  },
  {
    title: '所属院区',
    key: 'hospitalArea',
    width: 120
  },
  {
    title: '套餐价格(元)',
    key: 'price',
    width: 120
  },
  {
    title: '套餐项目',
    key: 'items',
    width: 200
  },
  {
    title: '状态',
    key: 'status',
    width: 80
  },
  {
    title: '操作',
    key: 'action',
    width: 120,
    align: 'center'
  }
]

// 套餐列表数据
const packageList = ref([])

// API配置
const uploadUrl = '/api/upload'

// 生命周期钩子
onMounted(() => {
  fetchPackageList()
})

// 获取套餐类型标签
const getTypeLabel = (type: string) => {
  const item = packageTypes.find(t => t.value === type)
  return item?.label || type
}

// 获取院区标签
const getAreaLabel = (area: string) => {
  const item = hospitalAreas.find(a => a.value === area)
  return item?.label || area
}

// 获取项目标签
const getItemLabel = (item: string) => {
  const checkupItem = checkupItems.find(i => i.value === item)
  return checkupItem?.label || item
}

// 获取套餐列表
const fetchPackageList = async () => {
  isLoading.value = true
  try {
    const response = await packageApi.getList({
      ...searchForm,
      page: currentPage.value,
      pageSize: pageSize.value
    })
    packageList.value = response.data || []
    total.value = response.total || 0
  } catch (error) {
    Message.error('获取套餐列表失败，请稍后再试')
  } finally {
    isLoading.value = false
  }
}

// 搜索套餐
const searchPackages = () => {
  currentPage.value = 1
  fetchPackageList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.type = ''
  searchForm.hospitalArea = ''
  searchForm.status = ''
  searchPackages()
}

// 编辑套餐
const editPackage = (record: any) => {
  isEditing.value = true
  // 复制数据到编辑表单
  Object.assign(editForm, {
    ...record,
    items: record.items ? record.items.split(',') : []
  })
  editModalVisible.value = true
}

// 删除套餐
const deletePackage = async (record: any) => {
  const confirmResult = await Message.confirm(
    '确定要删除此套餐吗？此操作不可撤销。',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
  
  if (confirmResult === 'confirm') {
    try {
      await packageApi.delete(record.id)
      Message.success('套餐删除成功')
      fetchPackageList()
    } catch (error) {
      Message.error('套餐删除失败，请稍后再试')
    }
  }
}

// 切换套餐状态
const toggleStatus = async (record: any) => {
  try {
    await packageApi.toggleStatus(record.id, record.status)
    Message.success('套餐状态更新成功')
  } catch (error) {
    // 回滚状态
    record.status = !record.status
    Message.error('套餐状态更新失败，请稍后再试')
  }
}

// 保存套餐
const savePackage = async () => {
  // 表单验证
  const isValid = await validateForm()
  if (!isValid) return
  
  try {
    const formData = {
      ...editForm,
      items: editForm.items.join(',')
    }
    
    if (isEditing.value) {
      // 更新套餐
      await packageApi.getList(formData)
      Message.success('套餐更新成功')
    } else {
      // 新增套餐
      await packageApi.create(formData)
      Message.success('套餐添加成功')
    }
    
    fetchPackageList()
    hideEditModal()
  } catch (error) {
    Message.error(isEditing.value ? '套餐更新失败' : '套餐添加失败')
  }
}

// 表单验证
const validateForm = () => {
  return new Promise((resolve) => {
    // 这里应该使用iView的表单验证，示例代码
    resolve(true)
  })
}

// 隐藏编辑模态框
const hideEditModal = () => {
  editModalVisible.value = false
}

// 处理上传成功
const handleUploadSuccess = (response: any) => {
  if (response.code === 200) {
    editForm.imageUrl = response.data.url
    Message.success('图片上传成功')
  } else {
    Message.error('图片上传失败')
  }
}

// 上传前处理
const beforeUpload = (file: File) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJPG) {
    Message.error('请上传JPG/PNG格式的图片')
    return false
  }
  
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    Message.error('图片大小不能超过2MB')
    return false
  }
  
  return true
}

// 处理分页变化
const handlePageChange = (page: number) => {
  currentPage.value = page
  fetchPackageList()
}

// 处理每页数量变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchPackageList()
}
</script>

<style scoped>
/* 自定义样式 */
.table-operations {
  margin-bottom: 16px;
}

.table-operations > button {
  margin-right: 8px;
}
</style>    